import React, { useEffect, useState } from 'react';
import { ProForm, ProFormText, ProFormTextArea, ProFormSelect } from '@ant-design/pro-components';
import { Card, message, Form, Divider, Tabs, Modal, Button, List, Space, Typography, Input, Empty, Tag } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import api from '../../services/api';
import { Agent, AgentPredefinedPrompt, User, Team, KnowledgeBase, Plugin, AgentPluginConfig, LlmModel } from '../../types';
import { llmModelService } from '../../services/llmModels';
import { useTranslation } from 'react-i18next';
import PluginConfiguration from '../../components/PluginConfiguration';
import KnowledgeBaseSelector from '../../components/KnowledgeBaseSelector';

const { Text } = Typography;

const AgentForm: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [loading, setLoading] = useState(false);
  const [initialValues, setInitialValues] = useState<Partial<Agent>>();
  const [users, setUsers] = useState<User[]>([]);
  const [teams, setTeams] = useState<Team[]>([]);
  const [knowledgeBases, setKnowledgeBases] = useState<KnowledgeBase[]>([]);
  const [plugins, setPlugins] = useState<Plugin[]>([]);
  const [llmModels, setLlmModels] = useState<LlmModel[]>([]);
  const [pluginConfigs, setPluginConfigs] = useState<AgentPluginConfig[]>([]);
  const [predefinedPrompts, setPredefinedPrompts] = useState<AgentPredefinedPrompt[]>([]);
  const [promptModalVisible, setPromptModalVisible] = useState(false);
  const [editingPromptIndex, setEditingPromptIndex] = useState<number | null>(null);
  const [promptForm] = Form.useForm();
  const [form] = Form.useForm();
  const isEdit = !!id;

  useEffect(() => {
    fetchUsers();
    fetchTeams();
    fetchKnowledgeBases();
    fetchPlugins();
    fetchLlmModels();
    if (isEdit) {
      fetchAgent();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [id]);

  const fetchUsers = async () => {
    try {
      const response = await api.get('/users/', { params: { skip: 0, limit: 1000 } });
      const usersData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setUsers(usersData);
    } catch (error: any) {
      message.error('Failed to fetch users');
      setUsers([]);
    }
  };

  const fetchTeams = async () => {
    try {
      const response = await api.get('/teams/', { params: { skip: 0, limit: 1000 } });
      const teamsData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setTeams(teamsData);
    } catch (error: any) {
      message.error('Failed to fetch teams');
      setTeams([]);
    }
  };

  const fetchKnowledgeBases = async () => {
    try {
      const response = await api.get('/knowledge-bases/', { params: { skip: 0, limit: 1000 } });
      const kbData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setKnowledgeBases(kbData);
    } catch (error: any) {
      message.error('Failed to fetch knowledge bases');
      setKnowledgeBases([]);
    }
  };

  const fetchPlugins = async () => {
    try {
      const response = await api.get('/plugins/', { params: { skip: 0, limit: 1000 } });
      const pluginsData = Array.isArray(response.data) ? response.data : response.data.items || [];
      setPlugins(pluginsData);
    } catch (error: any) {
      message.error('Failed to fetch plugins');
      setPlugins([]);
    }
  };

  const fetchLlmModels = async () => {
    try {
      const models = await llmModelService.getLlmModels();
      // Only show enabled models
      const enabledModels = models.filter(model => model.isEnabled);
      setLlmModels(enabledModels);
    } catch (error: any) {
      message.error('Failed to fetch LLM models');
      setLlmModels([]);
    }
  };

  const normalizePredefinedPrompts = (prompts: any): AgentPredefinedPrompt[] => {
    if (!prompts) {
      return [];
    }

    let parsed = prompts;
    if (typeof prompts === 'string') {
      try {
        parsed = JSON.parse(prompts);
      } catch (error) {
        console.warn('Failed to parse predefined prompts JSON:', error);
        parsed = [];
      }
    }

    if (!Array.isArray(parsed)) {
      return [];
    }

    return parsed
      .map((prompt: any) => {
        if (typeof prompt === 'string') {
          return {
            name: prompt,
            description: '',
            content: prompt,
          } as AgentPredefinedPrompt;
        }

        return {
          name: (prompt?.name ?? '').toString(),
          description: prompt?.description ? prompt.description.toString() : '',
          content: (prompt?.content ?? '').toString(),
        } as AgentPredefinedPrompt;
      })
      .filter((prompt: AgentPredefinedPrompt) => prompt.name || prompt.description || prompt.content);
  };

  const fetchAgent = async () => {
    try {
      const response = await api.get(`/agents/${id}`);
      const agentData = response.data;
      const normalizedPrompts = normalizePredefinedPrompts(agentData.predefinedPrompts || agentData.predefined_prompts);
      
      // 转换字段名称：后端返回 camelCase，前端期望 snake_case
      const normalizedAgent = {
        ...agentData,
        predefinedPrompts: normalizedPrompts,
        ve_admins: agentData.adminUserIds || agentData.ve_admins || [],
        team_access: agentData.teamAccessIds || agentData.team_access || [],
        knowledge_bases: agentData.knowledgeBaseIds || agentData.knowledge_bases || [],
        system_prompt: agentData.systemMetaPrompt || agentData.system_prompt,
        model_name: agentData.modelVersion || agentData.model_name,
        model_provider: agentData.modelProvider || agentData.model_provider,
      };
      
      setInitialValues(normalizedAgent);
      setPredefinedPrompts(normalizedPrompts);

      // Load plugin configurations if available
      if (agentData.pluginConfigurations || agentData.plugin_configurations) {
        setPluginConfigs(agentData.pluginConfigurations || agentData.plugin_configurations);
      }

      form.setFieldsValue({
        ...normalizedAgent,
        plugin_configurations: agentData.pluginConfigurations || agentData.plugin_configurations,
      });
    } catch (error: any) {
      message.error('Failed to fetch agent details');
      navigate('/agents');
    }
  };

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const sanitizedPrompts: AgentPredefinedPrompt[] = predefinedPrompts
        .map((prompt: AgentPredefinedPrompt) => ({
          name: (prompt?.name ?? '').trim(),
          description: (prompt?.description ?? '').trim(),
          content: (prompt?.content ?? '').trim(),
        }))
        .filter(prompt => prompt.name && prompt.content);

      // 提取 knowledge base IDs
      const knowledgeBaseIds = values.knowledge_bases || [];
      
      // 提取 plugin IDs 从 plugin configurations
      const pluginIds = pluginConfigs.map(config => config.pluginId);

      const requestPayload = {
        name: values.name,
        category: values.category,
        icon: values.icon,
        description: values.description,
        systemMetaPrompt: values.system_prompt || values.systemMetaPrompt || '',
        welcomeMessage: values.welcomeMessage || values.welcome_message,
        modelVersion: values.model_name || values.modelVersion || '',
        isPublic: values.isPublic || values.is_public || false,
        adminUserIds: values.ve_admins || [],
        teamAccessIds: values.team_access || [],
        knowledgeBaseIds: knowledgeBaseIds,
        pluginIds: pluginIds,
        predefinedPrompts: sanitizedPrompts.length > 0 ? JSON.stringify(sanitizedPrompts) : null,
        // 使用 camelCase 匹配后端 DTO
        pluginConfigurations: pluginConfigs.length > 0 ? pluginConfigs : undefined,
      };

      if (isEdit) {
        await api.put(`/agents/${id}`, requestPayload);
        message.success('Agent updated successfully');
      } else {
        await api.post('/agents/', requestPayload);
        message.success('Agent created successfully');
      }
      navigate('/agents');
    } catch (error: any) {
      message.error(error.response?.data?.detail || `Failed to ${isEdit ? 'update' : 'create'} agent`);
    } finally {
      setLoading(false);
    }
  };

  const handleOpenPromptModal = (index?: number) => {
    if (index !== undefined) {
      const prompt = predefinedPrompts[index];
      setEditingPromptIndex(index);
      promptForm.setFieldsValue({
        name: prompt.name,
        description: prompt.description || '',
        content: prompt.content,
      });
    } else {
      setEditingPromptIndex(null);
      promptForm.resetFields();
    }
    setPromptModalVisible(true);
  };

  const handleSavePrompt = async () => {
    try {
      const values = await promptForm.validateFields();
      const newPrompt: AgentPredefinedPrompt = {
        name: values.name.trim(),
        description: values.description?.trim() || '',
        content: values.content.trim(),
      };

      if (editingPromptIndex !== null) {
        const updated = [...predefinedPrompts];
        updated[editingPromptIndex] = newPrompt;
        setPredefinedPrompts(updated);
      } else {
        setPredefinedPrompts([...predefinedPrompts, newPrompt]);
      }

      setPromptModalVisible(false);
      promptForm.resetFields();
      setEditingPromptIndex(null);
      message.success(t('agent.promptSaved'));
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  const handleDeletePrompt = (index: number) => {
    const updated = predefinedPrompts.filter((_, i) => i !== index);
    setPredefinedPrompts(updated);
    message.success(t('agent.promptDeleted'));
  };

  const handleCancelPromptModal = () => {
    setPromptModalVisible(false);
    promptForm.resetFields();
    setEditingPromptIndex(null);
  };

  const userOptions = (users || []).map((user) => ({
    label: `${user.username} (${user.email})`,
    value: user.id,
  }));

  const teamOptions = (teams || []).map((team) => ({
    label: team.name,
    value: team.id,
  }));

  const modelOptions = (llmModels || []).map((model) => ({
    label: `${model.name} (${model.modelId}) - ${model.provider}`,
    value: model.modelId,
    provider: model.provider,
  }));

  return (
    <Card title={isEdit ? t('agent.edit') : t('agent.create')}>
      <ProForm
        form={form}
        initialValues={initialValues}
        onFinish={handleSubmit}
        loading={loading}
        submitter={{
          searchConfig: {
            submitText: isEdit ? t('common.update') : t('common.create'),
          },
          resetButtonProps: {
            onClick: () => navigate('/agents'),
          },
        }}
      >
        <Tabs
          defaultActiveKey="basic"
          items={[
            {
              key: 'basic',
              label: t('agent.basicInfoAndPermissions'),
              children: (
                <>
                  <ProFormText
                    name="name"
                    label={t('agent.name')}
                    placeholder={t('agent.namePlaceholder')}
                    rules={[{ required: true, message: t('agent.nameRequired') }]}
                  />

                  <ProFormSelect
                    name="category"
                    label={t('agent.category')}
                    options={[
                      { label: t('agent.categoryCustomerService'), value: 'Customer Service' },
                      { label: t('agent.categoryDataAnalysis'), value: 'Data Analysis' },
                      { label: t('agent.categoryCodeAssistant'), value: 'Code Assistant' },
                      { label: t('agent.categoryContentCreation'), value: 'Content Creation' },
                      { label: t('agent.categoryResearch'), value: 'Research' },
                      { label: t('agent.categoryTranslation'), value: 'Translation' },
                      { label: t('agent.categoryOther'), value: 'Other' },
                    ]}
                    placeholder={t('agent.categoryPlaceholder')}
                    fieldProps={{
                      showSearch: true,
                      allowClear: true,
                    }}
                  />

                  <ProFormSelect
                    name="icon"
                    label={t('agent.icon')}
                    options={[
                      { label: `🤖 ${t('agent.iconRobot')}`, value: 'RobotOutlined' },
                      { label: `👤 ${t('agent.iconCustomerService')}`, value: 'CustomerServiceOutlined' },
                      { label: `📊 ${t('agent.iconDataAnalysis')}`, value: 'BarChartOutlined' },
                      { label: `💻 ${t('agent.iconCode')}`, value: 'CodeOutlined' },
                      { label: `✍️ ${t('agent.iconEdit')}`, value: 'EditOutlined' },
                      { label: `🔍 ${t('agent.iconSearch')}`, value: 'SearchOutlined' },
                      { label: `📖 ${t('agent.iconBook')}`, value: 'BookOutlined' },
                      { label: `🌐 ${t('agent.iconGlobal')}`, value: 'GlobalOutlined' },
                      { label: `💡 ${t('agent.iconBulb')}`, value: 'BulbOutlined' },
                      { label: `🎯 ${t('agent.iconTarget')}`, value: 'AimOutlined' },
                    ]}
                    placeholder={t('agent.iconPlaceholder')}
                    fieldProps={{
                      showSearch: true,
                      allowClear: true,
                    }}
                  />

                  <ProFormTextArea
                    name="description"
                    label={t('agent.description')}
                    placeholder={t('agent.descriptionPlaceholder')}
                    fieldProps={{ rows: 4 }}
                  />

                  <ProFormSelect
                    name="ve_admins"
                    label={t('agent.admins')}
                    mode="multiple"
                    options={userOptions}
                    placeholder={t('agent.adminsPlaceholder')}
                    fieldProps={{
                      showSearch: true,
                      filterOption: (input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
                    }}
                  />

                  <ProFormSelect
                    name="team_access"
                    label={t('agent.teamAccess')}
                    mode="multiple"
                    options={teamOptions}
                    placeholder={t('agent.teamAccessPlaceholder')}
                    fieldProps={{
                      showSearch: true,
                      filterOption: (input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
                    }}
                  />
                </>
              ),
            },
            {
              key: 'ai-config',
              label: t('agent.aiConfigAndPlugins'),
              children: (
                <>
                  <ProFormTextArea
                    name="system_prompt"
                    label={t('agent.systemPrompt')}
                    placeholder={t('agent.systemPromptPlaceholder')}
                    fieldProps={{ rows: 6 }}
                  />

                  <ProFormSelect
                    name="model_name"
                    label={t('agent.model')}
                    options={modelOptions}
                    placeholder={t('agent.selectModelPlaceholder')}
                    rules={[{ required: true, message: t('agent.selectModelPlaceholder') }]}
                    fieldProps={{
                      showSearch: true,
                      filterOption: (input, option) =>
                        (option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
                      onChange: (value, option: any) => {
                        if (option && option.provider) {
                          form.setFieldValue('model_provider', option.provider);
                        }
                      },
                    }}
                  />

                  <ProFormText
                    name="model_provider"
                    label={t('agent.modelProvider')}
                    placeholder={t('agent.modelProviderAutoFilled')}
                    disabled
                  />

                  <ProFormTextArea
                    name="welcomeMessage"
                    label={t('agent.welcomeMessage')}
                    placeholder={t('agent.welcomeMessagePlaceholder')}
                    fieldProps={{ rows: 3 }}
                  />

                  <Divider>{t('agent.knowledgeBases')}</Divider>

                  <Form.Item label=" " colon={false}>
                    <KnowledgeBaseSelector
                      knowledgeBases={knowledgeBases}
                      value={form.getFieldValue('knowledge_bases') || []}
                      onChange={(selectedIds) => {
                        form.setFieldValue('knowledge_bases', selectedIds);
                      }}
                    />
                  </Form.Item>

                  <Divider>{t('agent.pluginConfigurations')}</Divider>

                  <Form.Item label=" " colon={false}>
                    <PluginConfiguration
                      plugins={plugins}
                      value={pluginConfigs}
                      onChange={setPluginConfigs}
                    />
                  </Form.Item>
                </>
              ),
            },
            {
              key: 'predefined-prompts',
              label: t('agent.predefinedPrompts'),
              children: (
                <>
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                      <Text type="secondary">
                        {predefinedPrompts.length > 0 
                          ? `${t('agent.totalPrompts')}: ${predefinedPrompts.length}`
                          : t('agent.noPrompts')}
                      </Text>
                      <Button
                        type="primary"
                        icon={<PlusOutlined />}
                        onClick={() => handleOpenPromptModal()}
                      >
                        {t('agent.addPrompt')}
                      </Button>
                    </div>

                    {predefinedPrompts.length === 0 ? (
                      <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        description={t('agent.noPromptsDescription')}
                        style={{ padding: '40px 0' }}
                      />
                    ) : (
                      <List
                        bordered
                        dataSource={predefinedPrompts}
                        renderItem={(prompt, index) => (
                          <List.Item
                            style={{ 
                              padding: '16px 24px',
                              transition: 'background-color 0.3s',
                              cursor: 'pointer',
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.backgroundColor = '#fafafa';
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.backgroundColor = 'transparent';
                            }}
                            actions={[
                              <Button
                                key="edit"
                                type="text"
                                icon={<EditOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleOpenPromptModal(index);
                                }}
                              >
                                {t('common.edit')}
                              </Button>,
                              <Button
                                key="delete"
                                type="text"
                                danger
                                icon={<DeleteOutlined />}
                                onClick={(e) => {
                                  e.stopPropagation();
                                  handleDeletePrompt(index);
                                }}
                              >
                                {t('common.delete')}
                              </Button>,
                            ]}
                            onClick={() => handleOpenPromptModal(index)}
                          >
                            <List.Item.Meta
                              avatar={
                                <div
                                  style={{
                                    width: 40,
                                    height: 40,
                                    borderRadius: '8px',
                                    backgroundColor: '#1890ff',
                                    display: 'flex',
                                    alignItems: 'center',
                                    justifyContent: 'center',
                                    color: '#fff',
                                    fontSize: '18px',
                                    fontWeight: 'bold',
                                  }}
                                >
                                  {index + 1}
                                </div>
                              }
                              title={
                                <Space size="middle">
                                  <Text strong style={{ fontSize: '16px' }}>
                                    {prompt.name}
                                  </Text>
                                  {prompt.description && (
                                    <Tag color="blue">{t('agent.hasDescription')}</Tag>
                                  )}
                                </Space>
                              }
                              description={
                                <Space direction="vertical" size="small" style={{ width: '100%', marginTop: '8px' }}>
                                  {prompt.description && (
                                    <div>
                                      <Text type="secondary" style={{ fontSize: '13px' }}>
                                        {prompt.description}
                                      </Text>
                                    </div>
                                  )}
                                  <div
                                    style={{
                                      padding: '8px 12px',
                                      backgroundColor: '#f5f5f5',
                                      borderRadius: '4px',
                                      marginTop: '4px',
                                    }}
                                  >
                                    <Text
                                      ellipsis={{ tooltip: prompt.content }}
                                      style={{
                                        display: 'block',
                                        color: '#595959',
                                        fontSize: '13px',
                                        lineHeight: '1.6',
                                      }}
                                    >
                                      {prompt.content}
                                    </Text>
                                  </div>
                                </Space>
                              }
                            />
                          </List.Item>
                        )}
                      />
                    )}
                  </Space>
                  <Modal
                    title={editingPromptIndex !== null ? t('agent.editPrompt') : t('agent.addPrompt')}
                    open={promptModalVisible}
                    onOk={handleSavePrompt}
                    onCancel={handleCancelPromptModal}
                    width={600}
                    okText={t('common.save')}
                    cancelText={t('common.cancel')}
                  >
                    <Form
                      form={promptForm}
                      layout="vertical"
                      initialValues={{
                        name: '',
                        description: '',
                        content: '',
                      }}
                    >
                      <Form.Item
                        name="name"
                        label={t('agent.promptName')}
                        rules={[{ required: true, message: t('agent.promptNameRequired') }]}
                      >
                        <Input placeholder={t('agent.promptNamePlaceholder')} />
                      </Form.Item>
                      <Form.Item
                        name="description"
                        label={t('agent.promptDescription')}
                      >
                        <Input.TextArea
                          rows={3}
                          placeholder={t('agent.promptDescriptionPlaceholder')}
                        />
                      </Form.Item>
                      <Form.Item
                        name="content"
                        label={t('agent.promptContent')}
                        rules={[{ required: true, message: t('agent.promptContentRequired') }]}
                      >
                        <Input.TextArea
                          rows={4}
                          placeholder={t('agent.promptContentPlaceholder')}
                        />
                      </Form.Item>
                    </Form>
                  </Modal>
                </>
              ),
            },
          ]}
        />
      </ProForm>
    </Card>
  );
};

export default AgentForm;
